package com.neusoft.lohas.modules.upload;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONObject;

import sun.misc.BASE64Decoder;

import com.neusoft.lohas.common.config.Global;
import com.neusoft.lohas.common.utils.StringUtils;
import com.neusoft.lohas.modules.sys.entity.User;
import com.neusoft.lohas.modules.sys.utils.UserUtils;

public class UploadLogoServlet extends HttpServlet{
	
	private static final long serialVersionUID = 1L;
	
	
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * 文件上传请求处理
	 * @param request
	 * @param response
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = null;
		try {
			/**
			 * KindEditor JSP
			 * 
			 * 本JSP程序是演示程序，建议不要直接在实际项目中使用。
			 * 如果您确定直接使用本程序，使用之前请仔细确认相关安全设置。
			 * 
			 */
			
			//文件保存目录路径
			String savePath = Global.getConfig("upload.path") + "";

			//文件保存目录URL
			String saveUrl  = "/";

			//定义允许上传的文件扩展名
			HashMap<String, String> extMap = new HashMap<String, String>();
			extMap.put("logo", "gif,jpg,jpeg,png,bmp");
			extMap.put("image", "gif,jpg,jpeg,png,bmp");
			extMap.put("flash", "swf,flv");
			extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
			extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");

			//最大文件大小
			long maxSize = 20*1024*1024;

			response.setContentType("text/html; charset=UTF-8");
			out = response.getWriter();
			
			//获取社群个人文件目录
			String permissionsDir = "";
			User user = UserUtils.getUser();
			if (StringUtils.isNotBlank(user.getName())) {
				permissionsDir = String.valueOf(user.getId());
			}else {
				permissionsDir = "0";
			}
			
//			if(!ServletFileUpload.isMultipartContent(request)){
//				out.println(getError("请选择文件。"));
//				return;
//			}
			//检查目录
			File uploadDir = new File(savePath);
			if(!uploadDir.isDirectory()){
				out.println(getError("上传目录不存在。"));
				return;
			}
			//检查目录写权限
			if(!uploadDir.canWrite()){
				out.println(getError("上传目录没有写权限。"));
				return;
			}

			String dirName = "logo";
			if(!extMap.containsKey(dirName)){
				out.println(getError("目录名不正确。"));
				return;
			}
			//创建文件夹
			savePath += permissionsDir + "/" + dirName + "/";
			saveUrl += permissionsDir + "/" + dirName + "/";
			File saveDirFile = new File(savePath);
			if (!saveDirFile.exists()) {
				saveDirFile.mkdirs();
			}
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			String ymd = sdf.format(new Date());
			savePath += ymd + "/";
			saveUrl += ymd + "/";
			File dirFile = new File(savePath);
			if (!dirFile.exists()) {
				dirFile.mkdirs();
			}

			SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
			String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000);
			String _savePath = savePath + newFileName;
			
			String file_src = savePath + "_src.jpg";    //保存原图
			String filename162 = _savePath + "_162.jpg";  //保存162
			String filename48 = _savePath + "_48.jpg";  //保存48
			String filename20 = _savePath + "_20.jpg";  //保存20

			String pic=request.getParameter("pic");
			String pic1=request.getParameter("pic1");
			String pic2=request.getParameter("pic2");
			String pic3=request.getParameter("pic3");

			if(!pic.equals("")&&pic!=null){
				//原图
				File file = new File(file_src);
				FileOutputStream fout = null;
				fout = new FileOutputStream(file);
				fout.write(new BASE64Decoder().decodeBuffer(pic));
				fout.close();
			}
			if(!pic1.equals("")&&pic1!=null){
				//图1
				File file1 = new File(filename162);
				FileOutputStream fout1 = null;
				fout1 = new FileOutputStream(file1);
				fout1.write(new BASE64Decoder().decodeBuffer(pic1));
				fout1.close();
			}
			if(!pic2.equals("")&&pic2!=null){
				//图2
				File file2 = new File(filename48);
				FileOutputStream fout2 = null;
				fout2 = new FileOutputStream(file2);
				fout2.write(new BASE64Decoder().decodeBuffer(pic2));
				fout2.close();
			}
			if(!pic3.equals("")&&pic3!=null){
				//图3
				File file3 = new File(filename20);
				FileOutputStream fout3 = null;
				fout3 = new FileOutputStream(file3);
				fout3.write(new BASE64Decoder().decodeBuffer(pic3));
				fout3.close();
			}
			String picUrl = saveUrl + newFileName;

			out.println("{\"status\":1,\"picUrl\":\""+picUrl+"\"}"); //返回图片地址
		} catch (Exception e) {
			out.println(getError("上传文件失败。"));
			return;
		}
		
	}
	
	private String getError(String message) {
		JSONObject obj = new JSONObject();
		obj.put("error", 1);
		obj.put("message", message);
		return obj.toJSONString();
	}
}
